package sdw.ufal.p3.util;

import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import gov.tjpr.service.GenericService;
import gov.tjpr.struts.forms.ValidationUtils;

import org.ajaxtags.xml.AjaxXmlBuilder;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessages;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.struts.DispatchActionSupport;

public abstract class BaseDispatchActionSupport extends DispatchActionSupport
		implements Constants, ConstantsForward {

	/**
	 * Retorna o service de acordo com o nome informado
	 * 
	 * @param serviceName
	 * @return
	 */
	@SuppressWarnings(value = { "rawtypes" })
	public GenericService getService(String serviceName) {
		return (GenericService) WebApplicationContextUtils
				.getRequiredWebApplicationContext(getServletContext()).getBean(
						serviceName);
	}

	protected ActionForward ajaxSelect(HttpServletResponse response,
			@SuppressWarnings("rawtypes") List lista,
			String campoIdentificador, String campoDescricao) throws Exception {
		AjaxXmlBuilder ajaxXML = new AjaxXmlBuilder();
		ajaxXML.setEncoding("ISO-8859-1");
		ajaxXML.addItems(lista, campoDescricao, campoIdentificador);
		response.setContentType("text/xml");
		response.setHeader("Cache-Control", "no-cache");
		ServletOutputStream out = response.getOutputStream();
		out.print(ajaxXML.toString());
		out.close();
		return null;
	}

	protected void saveErrors(HttpServletRequest request, String... keys) {
		ActionMessages errors = new ActionMessages();
		for (String key : keys)
			ValidationUtils.add(errors, ActionMessages.GLOBAL_MESSAGE, key);
		saveErrors(request.getSession(false)/*
											 * if there's no session returns
											 * null
											 */, errors);
	}

	protected void saveMessages(HttpServletRequest request, String... keys) {
		ActionMessages messages = new ActionMessages();
		for (String key : keys)
			ValidationUtils.add(messages, ActionMessages.GLOBAL_MESSAGE, key);
		saveMessages(request.getSession(false)/*
											 * if there's no session returns
											 * null
											 */, messages);
	}

	protected void saveSucessMessage(HttpServletRequest request) {
		saveMessages(request, "Dados Registrados");
	}
	
	
}
